import { listEvaluationVoByPageUsingPost } from '@/services/backend/evaluationController';
import { listUserByPageUsingPost } from '@/services/backend/userController';
import { StarOutlined, TrophyOutlined, UserOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Avatar, Card, Col, Divider, Progress, Row, Spin, Tag, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import './style.less'; // 导入样式文件

const { Title, Paragraph } = Typography;
const { Meta } = Card;

// 扩展 API.EvaluationVO 类型以包含我们需要的额外属性
type EnhancedStudent = API.UserVO & {
  achievements?: string[];
  skills?: {
    name: string;
    level: number;
  }[];
  averageScore?: number;
  description?: string;
};

const ExcellentStudents: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [students, setStudents] = useState<EnhancedStudent[]>([]);

  const fetchExcellentStudents = async () => {
    try {
      setLoading(true);
      // 获取学生列表 - 修正参数名称 role -> userRole
      const studentRes = await listUserByPageUsingPost({
        role: 'user', // 修正参数名
        pageSize: 8,
        current: 1,
        sortField: 'create_time',
        sortOrder: 'desc',
      });

      if (studentRes.code === 0 && studentRes.data && studentRes.data.records) {
        const studentIds = studentRes.data.records.map((student) => student.id || 0);

        // 获取评估数据
        const evaluationPromises = studentIds.map((id) =>
          listEvaluationVoByPageUsingPost({
            studentId: id,
            pageSize: 10,
            current: 1,
          }),
        );

        const evaluationResults = await Promise.all(evaluationPromises);

        // 处理学生数据，添加成就和技能信息
        const enhancedStudents = studentRes.data.records.map((student, index) => {
          // 计算平均评分
          const evaluations = evaluationResults[index]?.data?.records || [];
          const scores = evaluations
            .map((evaluation) => evaluation.score)
            .filter((score) => score !== undefined);
          const averageScore =
            scores.length > 0
              ? scores.reduce((sum, score) => sum + (score || 0), 0) / scores.length
              : 0;

          // 模拟学生成就和技能数据
          const achievements = [
            '校园足球联赛最佳射手',
            '青少年足球锦标赛冠军',
            '技能训练营优秀学员',
          ].slice(0, Math.floor(Math.random() * 3) + 1);

          const skills = [
            { name: '传球', level: Math.floor(Math.random() * 30) + 70 },
            { name: '射门', level: Math.floor(Math.random() * 30) + 70 },
            { name: '盘带', level: Math.floor(Math.random() * 30) + 70 },
            { name: '防守', level: Math.floor(Math.random() * 30) + 70 },
          ];

          return {
            ...student,
            description: `${
              student.username || '学员'
            } 是一位充满潜力的足球新星，在训练中表现出色，具有良好的团队合作精神和出色的个人技术。`,
            achievements,
            skills,
            averageScore,
          };
        });

        // 按平均评分排序
        enhancedStudents.sort((a, b) => (b.averageScore || 0) - (a.averageScore || 0));
        setStudents(enhancedStudents);
      }
    } catch (error) {
      console.error('获取优秀学员数据失败', error);
    } finally {
      setLoading(false);
    }
  };

  // 将样式添加逻辑移到组件内部的 useEffect 中
  useEffect(() => {
    fetchExcellentStudents();

    // 添加全局样式
    const styleElement = document.createElement('style');
    styleElement.innerHTML = `
      .excellent-students-container .ant-pro-page-container-children-content {
        margin: 24px;
      }

      .student-card:hover {
        transform: translateY(-6px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
      }

      .student-card .ant-progress-bg {
        height: 8px !important;
        border-radius: 4px !important;
      }
    `;
    document.head.appendChild(styleElement);

    // 组件卸载时移除样式
    return () => {
      document.head.removeChild(styleElement);
    };
  }, []);

  return (
    <PageContainer
      header={{
        title: '优秀学员展示',
        subTitle: '展示在我们平台上表现突出的足球学员',
        ghost: true,
      }}
      className="excellent-students-container"
    >
      <div
        className="page-header"
        style={{
          textAlign: 'center',
          margin: '0 auto 40px',
          maxWidth: '800px',
          padding: '20px',
          background: 'linear-gradient(135deg, #1890ff 0%, #722ed1 100%)',
          borderRadius: '8px',
          color: 'white',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
        }}
      >
        <Title level={2} style={{ color: 'white', marginBottom: '16px' }}>
          <StarOutlined style={{ marginRight: '12px' }} />
          足球明日之星
        </Title>
        <Paragraph style={{ fontSize: '16px', color: 'rgba(255, 255, 255, 0.85)' }}>
          这些优秀学员在训练中展现出色的足球天赋和团队精神，是我们足球训练营的骄傲。
          通过专业教练的指导和自身的努力，他们在各项技能上都取得了显著的进步。
        </Paragraph>
      </div>

      <Spin spinning={loading}>
        <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
          {students.map((student, index) => (
            <Col xs={24} sm={12} md={8} lg={6} key={student.id || index}>
              <Card
                hoverable
                className="student-card"
                style={{
                  borderRadius: '12px',
                  overflow: 'hidden',
                  transition: 'all 0.3s',
                  boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
                  height: '100%',
                }}
                cover={
                  <div
                    style={{
                      padding: '30px 0',
                      textAlign: 'center',
                      background:
                        index < 3
                          ? `linear-gradient(135deg, #ffd700 0%, #ffb700 100%)`
                          : 'linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%)',
                      position: 'relative',
                    }}
                  >
                    {index < 3 && (
                      <div
                        style={{
                          position: 'absolute',
                          top: 0,
                          left: 0,
                          background: '#ff4d4f',
                          color: 'white',
                          padding: '4px 12px',
                          borderBottomRightRadius: '8px',
                          fontWeight: 'bold',
                          boxShadow: '2px 2px 5px rgba(0,0,0,0.2)',
                        }}
                      >
                        TOP {index + 1}
                      </div>
                    )}
                    {index < 3 && (
                      <TrophyOutlined
                        style={{
                          position: 'absolute',
                          top: 10,
                          right: 10,
                          fontSize: 28,
                          color: '#ff4d4f',
                          filter: 'drop-shadow(2px 2px 3px rgba(0,0,0,0.2))',
                        }}
                      />
                    )}
                    <Avatar
                      size={120}
                      src={student.avatar}
                      icon={<UserOutlined />}
                      style={{
                        border: index < 3 ? '4px solid #ff4d4f' : '4px solid #1890ff',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                      }}
                    />
                    <div style={{ marginTop: 16 }}>
                      <Title
                        level={4}
                        style={{ margin: 0, color: index < 3 ? '#d4380d' : '#1890ff' }}
                      >
                        {student.username || '未知学员'}
                      </Title>
                      <div
                        style={{
                          margin: '8px auto',
                          background: 'rgba(255,255,255,0.6)',
                          padding: '4px 12px',
                          borderRadius: '20px',
                          display: 'inline-block',
                          fontWeight: 'bold',
                        }}
                      >
                        平均评分: {student.averageScore?.toFixed(1) || '0.0'}/10
                      </div>
                    </div>
                  </div>
                }
              >
                <Meta
                  description={
                    <div style={{ padding: '8px 0' }}>
                      <Paragraph
                        ellipsis={{
                          rows: 2,
                          expandable: true,
                          symbol: '更多',
                        }}
                        style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.65)' }}
                      >
                        {student.description}
                      </Paragraph>

                      <Divider style={{ margin: '16px 0' }} />

                      <div style={{ marginTop: 16 }}>
                        <Title
                          level={5}
                          style={{
                            fontSize: '16px',
                            position: 'relative',
                            paddingLeft: '12px',
                            borderLeft: '3px solid #1890ff',
                            lineHeight: '20px',
                          }}
                        >
                          技能水平
                        </Title>
                        {student.skills?.map((skill) => (
                          <div key={skill.name} style={{ marginBottom: 12 }}>
                            <div
                              style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                marginBottom: '4px',
                              }}
                            >
                              <span style={{ fontWeight: 'bold' }}>{skill.name}</span>
                              <span>{skill.level}%</span>
                            </div>
                            <Progress
                              percent={skill.level}
                              size="small"
                              strokeColor={{
                                '0%': '#108ee9',
                                '100%': '#87d068',
                              }}
                              status={skill.level > 85 ? 'success' : 'active'}
                              showInfo={false}
                              style={{ height: '8px' }}
                            />
                          </div>
                        ))}
                      </div>

                      <div style={{ marginTop: 20 }}>
                        <Title
                          level={5}
                          style={{
                            fontSize: '16px',
                            position: 'relative',
                            paddingLeft: '12px',
                            borderLeft: '3px solid #1890ff',
                            lineHeight: '20px',
                          }}
                        >
                          成就
                        </Title>
                        <div style={{ marginTop: '8px' }}>
                          {student.achievements?.map((achievement) => (
                            <Tag
                              color="blue"
                              key={achievement}
                              style={{
                                margin: '0 8px 8px 0',
                                padding: '4px 8px',
                                borderRadius: '4px',
                              }}
                            >
                              {achievement}
                            </Tag>
                          ))}
                        </div>
                      </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Spin>

      {/* 删除 style jsx global 标签，改用 React 的方式添加样式 */}
    </PageContainer>
  );
};

export default ExcellentStudents;
